package com.example.asynctaskdemo;

import android.app.Activity;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ClipData;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import com.google.gson.Gson;
import com.kid.star.App;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by hukunge on 2016/6/14.
 */
public class Util {
    /**
     * 类型转换：string转long
     *
     * @param str
     * @param defaultVal
     * @return
     */
    public static long parseLong(String str, long defaultVal) {
        long result = defaultVal;
        try {
            result = Long.parseLong(str);
        } catch (NumberFormatException e) {
            result = defaultVal;
        }
        return result;
    }

    /**
     * 时间戳格式化成时间
     *
     * @param timeStamp
     * @return
     */
    public static String convertTimeStamp(long timeStamp) {
        Date date = new Date(timeStamp);
        String strs = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            strs = sdf.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strs;
    }

    /****
     * 强制关闭软键盘
     *
     * @param activity
     * @param view:接收软键盘的视图
     * @author hukunge
     */
    public static void hideKeyBoardForced(Activity activity, View view) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    public static String getVersionName() {
        String versionName = "";
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = App.getInstance().getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(App.getInstance().getPackageName(), 0);
            versionName = packInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            versionName = "";
        }
        return versionName;
    }

    /**
     * dip转像素
     *
     * @param dipValue
     * @return
     * @author hukunge
     */
    public static int dip2px(float dipValue) {
        final float scale = App.getInstance().getResources()
                .getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 像素转dip
     *
     * @param px
     * @return
     * @author hukunge
     */
    public static int px2dip(float px) {
        final float scale = App.getInstance().getResources()
                .getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /***
     * 获取手机状态栏高度
     *
     * @return
     * @author hukunge
     */
    public static int getStatusBarHeight() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = App.getInstance().getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    /***
     * 将聊天内容复制到系统剪切板
     */
    public static void copyContentToClipboard(String content) {
        if (ConsUtil.apiLeval < 11) {
            android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) App.getInstance()
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            clipboardManager.setText(content);
        } else {// 如果手机api大于等于11
            android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) App.getInstance()
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            clipboardManager.setPrimaryClip(ClipData
                    .newPlainText(null, content));
        }
    }

    public static String encodeUrlStr(String urlStr) {
        try {
            return java.net.URLEncoder.encode(urlStr, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static <T> T parseStr2Bean(String result, Type typeOfT) {
        T resultBean;
        Gson gson = new Gson();
        try {
            resultBean = gson.fromJson(result, typeOfT);
        } catch (Exception e) {
            e.printStackTrace();
            resultBean = null;
        }
        return resultBean;
    }

    public static String getUniqueDeviceId() {
        // The IMEI: 仅仅只对Android手机有效:
        //权限：android.permission.READ_PHONE_STATE
        TelephonyManager TelephonyMgr = (TelephonyManager) App.getInstance().getSystemService(Context.TELEPHONY_SERVICE);
        String szImei = TelephonyMgr.getDeviceId();

        //Pseudo-Unique ID, 这个在任何Android手机中都有效
        String m_szDevIDShort = "35" + //we make this look like a valid IMEI
                Build.BOARD.length() % 10 +
                Build.BRAND.length() % 10 +
                Build.CPU_ABI.length() % 10 +
                Build.DEVICE.length() % 10 +
                Build.DISPLAY.length() % 10 +
                Build.HOST.length() % 10 +
                Build.ID.length() % 10 +
                Build.MANUFACTURER.length() % 10 +
                Build.MODEL.length() % 10 +
                Build.PRODUCT.length() % 10 +
                Build.TAGS.length() % 10 +
                Build.TYPE.length() % 10 +
                Build.USER.length() % 10; //13 digits

        //The Android ID
        //Returns: 9774d56d682e549c . 无需任何许可。
        String m_szAndroidID = Settings.Secure.getString(App.getInstance().getContentResolver(), Settings.Secure.ANDROID_ID);

        //The WLAN MAC Address string
        //权限：android.permission.ACCESS_WIFI_STATE
        WifiManager wm = (WifiManager) App.getInstance().getSystemService(Context.WIFI_SERVICE);
        String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();

        //The BT MAC Address string
        //权限：android.permission.BLUETOOTH
        BluetoothAdapter m_BluetoothAdapter = null; // Local Bluetooth adapter
        m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        String m_szBTMAC = m_BluetoothAdapter.getAddress();


        //通过以上算法，可产生32位的16进制数据:9DDDF85AFF0A87974CE4541BD94D5F55
        String m_szLongID = szImei + m_szDevIDShort
                + m_szAndroidID + m_szWLANMAC + m_szBTMAC;
        // compute md5
        MessageDigest m = null;
        try {
            m = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        m.update(m_szLongID.getBytes(), 0, m_szLongID.length());
        // get md5 bytes
        byte p_md5Data[] = m.digest();
        // create a hex string
        String m_szUniqueID = new String();
        for (int i = 0; i < p_md5Data.length; i++) {
            int b = (0xFF & p_md5Data[i]);
            // if it is a single digit, make sure it have 0 in front (proper padding)
            if (b <= 0xF)
                m_szUniqueID += "0";
            // add number to string
            m_szUniqueID += Integer.toHexString(b);
        }   // hex string to uppercase
        m_szUniqueID = m_szUniqueID.toUpperCase();

        return m_szUniqueID;
    }


    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 50, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


    /**
     * 随机指定范围内N个不重复的数
     * 在初始化的无重复待选数组中随机产生一个数放入结果中，
     * 将待选数组被随机到的数，用待选数组(len-1)下标对应的数替换
     * 然后从len-2里随机产生下一个随机数，如此类推
     *
     * @param max 指定范围最大值
     * @param min 指定范围最小值
     * @param n   随机数个数
     * @return int[] 随机数结果集
     */
    public static String randomArray(int min, int max, int n) {
        int len = max - min + 1;

        if (max < min || n > len) {
            return null;
        }

        //初始化给定范围的待选数组
        int[] source = new int[len];
        for (int i = min; i < min + len; i++) {
            source[i - min] = i;
        }

        int[] result = new int[n];
        Random rd = new Random();
        int index = 0;
        for (int i = 0; i < result.length; i++) {
            //待选数组0到(len-2)随机一个下标
            index = Math.abs(rd.nextInt() % len--);
            //将随机到的数放入结果集
            result[i] = source[index];
            //将待选数组中被随机到的数，用待选数组(len-1)下标对应的数替换
            source[index] = source[len];
        }

        String s = "";
        for (int a = 0; a < result.length; a++) {
            s += result[a];
        }

        return s;
    }

    public static boolean isForeGround(String packageName) {
        Context context = App.getInstance();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }
}
